package com.tuo51.childcare.service.Template;

import com.tuo51.childcare.service.WxPushService;
import com.tuo51.evaluate.domain.childrens.Children;
import com.tuo51.evaluate.domain.evaluatingV2.EvaluateV2Record;
import com.tuo51.core.domain.staffs.Staff;
import com.tuo51.evaluate.service.ChildrenService;
import com.tuo51.core.service.StaffService;
import com.tuo51.foudation.constant.CommonConstant;
import com.tuo51.foudation.exception.BusinessException;
import com.tuo51.foudation.model.ErrorCode;
import com.tuo51.foudation.utils.DateUtil;
import com.tuo51.observation.domain.ObservateRecord;
import com.tuo51.wx.mp.config.WxMpProperties;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.*;

@EnableConfigurationProperties(WxMpProperties.class)
@Slf4j
@Service
public class WxPushServiceImpl implements WxPushService {

    @Autowired
    private WxMpProperties properties;

    @Autowired
    private WxMpService wxService;

    @Autowired
    private ChildrenService childrenService;

    @Autowired
    private StaffService staffService;

    @Value("${wx.mp.push.link_url}")
    private  String wxPushLinkUrl;

    @Autowired
    private WxMpProperties mpProperties;

    private static final int EVALUATE_TEMPLATE_INDEX = 0;
    private static final int OBSERVATEPOINT_TEMPLATE_INDEX = 1;

    public List<String> send(WxTemplate template, String channel, String childrenId){

        if(StringUtils.isEmpty(channel) || !channel.equals(properties.getChannel()) ){
            throw new BusinessException(ErrorCode.GENRAL_INTERNAL_ERROR, "channel not supported");
        }

        //根据areaid获取园区配置
        Children children = childrenService.getById(childrenId);
        if(children == null) {
            throw new BusinessException(ErrorCode.CHILDREN_NOT_EXIST, "children not exist");
        }

        String areaId = null;
        String areaAppId = null;
        String areaAppSecret = null;

        String sourceAppId = null;
        boolean defaultSourceApp = true;
        //如果存在，则忽略其他的
        if(StringUtils.isNotEmpty(areaAppId)){
            if( StringUtils.isEmpty(areaAppSecret)){
                throw new BusinessException(ErrorCode.GENRAL_INTERNAL_ERROR, "vip mp config failed");
            }
            //使用园区配置
            sourceAppId = areaAppId;
            defaultSourceApp = false;

            //园区appId生效，则使用园区模板id
            template.setTemplateId(translateTemplateIdToVIPTemplateId(areaId, template.getTemplateId()));

            //跳转地址重新设置
            template.setUrl(translateJumpURLToVipAreaURL(areaId, template.getUrl()));
        }else{
            //不存在则使用预置的appid
            //return StatusResponse.error(ErrorCode.WX_AREA_MP_CONFIG_FAILED, "园区areaId配置错误")
            sourceAppId = properties.getConfigs().get(0).getAppId();
        }

        List<Staff> parents = staffService.getByPhone(children.getExtendInfo().getGuardianPhone(), null, CommonConstant.Platform.WXMP.codeOf());

        if(parents.size() == 0){
            log.warn("try to push a non-binding children " + childrenId + ">>>" + sourceAppId + ":::" + defaultSourceApp);
            return new ArrayList<>();
        }

        String[] toUserIds = parents.stream().filter(o -> StringUtils.isNotEmpty(o.getOpenidMP())).map(o -> {
            return o.getOpenidMP();
        }).toArray(String[]::new);

        String toUserIdsStr = StringUtils.join(toUserIds, ',');

        template.setTouser(toUserIdsStr);

        List<String> result = doSend(template, areaAppId, areaAppSecret);

        return result;
    }

    private String translateTemplateIdToVIPTemplateId(String areaId, String officialTemplateId){
        return officialTemplateId;
//        Map<String, String> ids = portalService.getMpTemplateIds(areaId);
//        String ret = ids.get(officialTemplateId);
//
//        if(StringUtils.isEmpty(ret)){
//            throw  new BusinessException(ErrorCode.UNDEFINED, "VIP template id not found");
//        }
//
//        return ret;
    }

    private String translateJumpURLToVipAreaURL(String areaId, String officialURL){
//        if(StringUtils.isBlank(officialURL)){
//            return officialURL;
//        }
//
//        //2c90805b6cacba9c016cbd62592e00f0.vip.mp.starinside.net
//        //2c90805b6cacba9c016cbd62592e00f0.vip.mp.dev.starinside.net
//        String officialHost = properties.getHost();
////        if(officialURL.indexOf(officialHost) > 0){
////            officialURL = officialURL.replace("//mp.", String.format("//%s.vip.mp.", areaId));
////        }
//        if(officialURL.indexOf(officialHost) >= 0){
//            officialURL = officialURL.replace("//mp.", String.format("//%s.vip.mp.", areaId));
//            officialURL = officialURL.replace(".starinside.cn/", ".starinside.net/");
//        }

        return officialURL;
    }

    /**
     * 通用模版接口，不涉及具体业务模版
     * @param template
     * @return
     */
    public List<String> send(@RequestBody WxTemplate template){
        log.info("template:send",template.toString());

        List<String> result = doSend(template, null, null);

        return result;
    }

    public List<String> doSend(WxTemplate template, String forceAppId, String forceAppSecret){
        String[] userList = template.getTouser().split(",");

        List<String> errList = new ArrayList<>();

        for (String user:userList){
            WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
            templateMessage.setToUser(user);

            templateMessage.setTemplateId(template.getTemplateId());
            templateMessage.setUrl(template.getUrl());
            for (int i=0;i<template.data.size();i++){
                WxTemplateItem item = template.getData().get(i);
                List<WxMpTemplateData> data = templateMessage.getData();
                if(data == null){
                    data = new ArrayList<>();
                    templateMessage.setData(data);
                }
                data.add(new WxMpTemplateData(item.getName(), item.getValue(), item.getColor()));
            }

            try {
                String ret = null;

                if(StringUtils.isNotEmpty(forceAppId) && StringUtils.isEmpty(forceAppSecret)) {
                    ret = wxService.switchoverTo(forceAppId).getTemplateMsgService().sendTemplateMsg(templateMessage);
                }else
                if(StringUtils.isEmpty(forceAppId) && StringUtils.isEmpty(forceAppSecret)) {
                    ret = wxService.getTemplateMsgService().sendTemplateMsg(templateMessage);
                }else{
//                    vipWxService.makeVIPAppIdValid(forceAppId, forceAppSecret);
//                    ret = vipWxService.getTemplateMsgService().sendTemplateMsg(templateMessage);
                }

                log.info("msg send result ::: " + ret);
                errList.add(ret);
            } catch (WxErrorException e) {
                e.printStackTrace();
                errList.add("");
            }
        }

        return errList;
    }


    public List<String> pushToParentsWithEvaluateRecord(Staff parent, EvaluateV2Record evaluateRecord){
        // FIXME:  这个url要替换
        String jumpUrl = wxPushLinkUrl + "/assessExpert?evaluateRecordId=" + evaluateRecord.getId();

        String appId = parent.getSourceAppId();
        List<String> templates = mpProperties.getTemplates().get(appId);
        String templateId = templates.get(EVALUATE_TEMPLATE_INDEX);

        Date evaluateRecordDate = evaluateRecord.getCreated();
        Calendar cal = Calendar.getInstance();
        cal.setTime(evaluateRecordDate);
        int evaluateRecordMonth = cal.get(Calendar.MONTH)+1; //注意月份是从0开始的

        String firstText = "您的宝宝" + evaluateRecordMonth + "月份心理行为测评已经发布!";
        String evaluateRecordDateStr = DateUtil.parseToDate(evaluateRecordDate);

        WxTemplate wxTemplate = new WxTemplate();
        wxTemplate.setTemplateId(templateId);
        wxTemplate.setUrl(jumpUrl);
        wxTemplate.setTouser(parent.getOpenidMP());

//        {{first.DATA}}
//        测评类型：{{keyword1.DATA}}
//        测评结果：{{keyword2.DATA}}
//        {{remark.DATA}}

        WxTemplateItem item1 = WxTemplateItem.of("keyword1", "心理行为评测", "#743A3A");
        WxTemplateItem item2 = WxTemplateItem.of("keyword2", evaluateRecord.getRating(), "#743A3A");

        WxTemplateItem first = WxTemplateItem.of("first", firstText, "#743A3A");
        WxTemplateItem remark = WxTemplateItem.of("remark", "若有疑问，请及时联系测评机构或测评师！", "#743A3A");

        List<WxTemplateItem> items = Arrays.asList(item1, item2, remark, first);

        wxTemplate.setData(items);

        return doSend(wxTemplate, parent.getSourceAppId(), null);
    }

    @Override
    public List<String> pushObservationNewRecord(ObservateRecord record, Staff staff, Staff parent, Children children, String feedid){

        //observationDetail?recordId=123456789
        String jumpUrl = wxPushLinkUrl +"/observationDetail?recordId=" + (StringUtils.isEmpty(feedid) ? record.getId() : feedid);

        String appId = parent.getSourceAppId();
        List<String> templates = mpProperties.getTemplates().get(appId);
        String templateId = templates.get(OBSERVATEPOINT_TEMPLATE_INDEX);

        String dateStr = DateUtil.parseToDate(new Date());
        String teacherName = staff.getRealName();
        String firstText = "亲爱的家长，"+children.getName()+"宝贝今天的一日观察记录请查收！";
        String remarkText = children.getName() + "宝贝最新一日观察记录新鲜出炉啦，老师都竖起了大拇指，继续加油！~ 快点击详情查看具体内容吧~";

        WxTemplate wxTemplate = new WxTemplate();
        wxTemplate.setTemplateId(templateId);
        wxTemplate.setUrl(jumpUrl);
        wxTemplate.setTouser(parent.getOpenidMP());

        WxTemplateItem item1 = WxTemplateItem.of("keyword1", "活动观测报告", "#743A3A");
        WxTemplateItem item2 = WxTemplateItem.of("keyword2", teacherName, "#743A3A");
        WxTemplateItem item3 = WxTemplateItem.of("keyword3", dateStr, "#743A3A");

        WxTemplateItem first = WxTemplateItem.of("first", firstText, "#743A3A");
        WxTemplateItem remark = WxTemplateItem.of("remark", remarkText, "#743A3A");

        List<WxTemplateItem> items = Arrays.asList(item1, item2, item3, remark, first);

        wxTemplate.setData(items);

        return doSend(wxTemplate, parent.getSourceAppId(), null);
    }
}
